﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vit.SchemaExplorer;
using Vit.Common.Extensions;

namespace Vit.Data
{
    public class SqlSelect : SqlStatement
    {
        public SqlSelect()
        {
            Columns = new List<SqlObject>();
            Joins = new List<SqlJoin>();
            From = new SqlFrom();
        }

        public override string ToSql()
        {
            if(Columns.Count <= 0)
                throw new NullReferenceException(Resources.SelectColumnsCannotBeNull);
            if(From ==null)
                throw new NullReferenceException(Resources.SelectFromCannotBeNull);

            StringBuilder sql = new StringBuilder("SELECT ");
            foreach (var col in Columns)
            {
                sql.Append(col.ToSql()).Append(", ");
            }
            sql.Remove(sql.Length - 2, 2).Append(" ");
            sql.Append(From.ToSql()).Append(" ");
            if (Joins != null && Joins.Count > 0)
            {
                foreach (var join in Joins)
                {
                    sql.Append(join.ToSql()).Append(" ");
                }
            }
            if (Where != null)
                sql.Append(Where.ToSql()).Append(" ");

            return sql.ToString().Trim();
        }

        public List<SqlObject> Columns { get; set; }
        public SqlFrom From { get; set; }
        public List<SqlJoin> Joins { get; set; }
        public SqlWhere Where { get; set; }
    }
}
